var storage = window.sessionStorage;

function setUserRole(userRole) {
    storage.removeItem("userRole");
    storage.setItem("userRole", JSON.stringify(userRole));
};

function setStorage(key, value) {
    storage.removeItem(key);
    storage.setItem(key, JSON.stringify(value));
}

function getStorage(key) {
    var val = JSON.parse(storage.getItem(key));
    return val == null ? '' : val;
}

function getAndRemoveStorage(key) {
    var val = getStorage(key);
    removeStorage(key);
    return val;
}

function getSettingStatus() {
    return getStorage("setting-status");
}

function setSettingStatus(value) {
    storage.removeItem("setting-status");
    storage.setItem("setting-status", JSON.stringify(value));
}


function removeStorage(key) {
    storage.removeItem(key);
}

function setUserName(userName) {
    storage.removeItem("userName");
    storage.setItem("userName", JSON.stringify(userName));
};

function setTokenId(tokenId) {
    storage.removeItem("tokenId");
    storage.setItem("tokenId", JSON.stringify(tokenId));
};


function setUserId(userId) {
    storage.removeItem("userId");
    storage.setItem("userId", JSON.stringify(userId));
};

function setUserAccount(userAccount) {
    storage.removeItem("userAccount");
    storage.setItem("userAccount", JSON.stringify(userAccount));
};

function getUserAccount() {
    var val = JSON.parse(storage.getItem("userAccount"));
    return val == null ? '' : val;
};

function getUserName() {
    var val = JSON.parse(storage.getItem("userName"));
    return val == null ? '' : val;
};

function getUserRole() {
    var val = JSON.parse(storage.getItem("userRole"));
    return val == null ? '' : val;
};

function getTokenId() {
    var val = JSON.parse(storage.getItem("tokenId"));
    return val == null ? '' : val;
};

function getUserId() {
    var val = JSON.parse(storage.getItem("userId"));
    return val == null ? '' : val;
};

function trimAll(str) {
    return str = str.replace(/\s/g, "")
}

function arrayContains(array, obj) {
    if (array.length == 0) {
        return false;
    }
    for (var i = 0; i < array.length; i++) {
        if (array[i] === obj) {
            return true;
        }
    }
    return false;
};

function getTemplateUrl(url) {
    return url + matrix_global_random;
};

//缓存用户偏好
function saveFondness(fondness) {
    setStorage(getUserAccount() + '_fondness', fondness)
};

/**
 * 获取缓存的偏好 目前只保存两个url的偏好
 * param 可选值 ： "/api/v1/issue/getIssues"、"/api/v1/brdRequirement/getBrdRequirements"
 */
function getFondness(param) {
    var fondness = getStorage(getUserAccount() + '_fondness')
    if (fondness == '') {
        return null;
    }
    if (fondness[param] == undefined) {
        return null;
    }
    return fondness[param];
};

function timestampToTime(timestamp, dateType) {
    var userAgent = navigator.userAgent;
    // 判断是否Safari浏览器  
    if (angular.isString(timestamp) && userAgent.indexOf("Safari") > -1) {  
        return timestamp;
    } else {
        if (timestamp) {
            var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
            Y = date.getFullYear() + '-';
            M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
            h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
            m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
            s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
            return dateType ? (Y + M + D) : (Y + M + D + " " + h + m + s);
        } else {
            return "";
        }
    }
}

// 判断是否有相同元素
function isRepeat(arr) {
    return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test("\x0f"+arr.join("\x0f\x0f") +"\x0f");
}

// 获取排期时间
function getWeekArray() {
    var weekArray = new Array();
    angular.forEach(getYearAndMonth(), function(dateItem) {
        var weekCount = getWeeks(dateItem.year, dateItem.month);
        for(var i = 1; i <= weekCount; i++) {
            var info = getWeekTime(dateItem.year, dateItem.month, i);
            weekArray.push(info);
        }
    });
    return weekArray;
}

// 获取一年的月份数组(从当前月至下一年当前月止)
function getYearAndMonth() {
    var yearAndMonthArray = [];
    var date = new Date;
    var crtYear = date.getFullYear(); 
    var crtMonth = date.getMonth();
    for(var i = 1; i<=13; i++) {
        crtMonth++;
        if(crtMonth == 13) {
            crtMonth = 1;
            crtYear ++;
        }
        yearAndMonthArray.push({"year": crtYear, "month": crtMonth});
    }
    return yearAndMonthArray;
}

// 获取每月有几周
function getWeeks(year, month) {
    var d = new Date();
    // 该月第一天
    d.setFullYear(year, month-1, 1);
    var w1 = d.getDay();
    if (w1 == 0) w1 = 7;
    // 该月天数
    d.setFullYear(year, month, 0);
    var dd = d.getDate();
    // 第一个周一
    var d1;
    if (w1 != 1) d1 = 7 - w1 + 2;
    else d1 = 1;
    var week_count = Math.ceil((dd-d1+1)/7);
    return week_count;
}

// 根据年月日周获取周一至周日的日期
function getWeekTime(year, month, weekday) {
    var d = new Date();
    // 该月第一天
    d.setFullYear(year, month-1, 1);
    var w1 = d.getDay();
    if (w1 == 0) w1 = 7;
    // 该月天数
    d.setFullYear(year, month, 0);
    var dd = d.getDate();
    // 第一个周一
    var d1;
    if (w1 != 1) d1 = 7 - w1 + 2;
    else d1 = 1;
    var monday = d1+(weekday-1)*7;
    var sunday = monday + 6;
    var from = year+"-"+month+"-"+monday;
    var to;
    if (sunday <= dd) {
        to = year+"-"+month+"-"+sunday;
    } else {
        d.setFullYear(year, month-1, sunday);
        var days=d.getDate();
        to = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+days;
    }
    // console.log(month+"月，第"+ weekday +"周，开始日期："+ from + "，结束日期："+ to +"，周五时间戳："+ getMS(to));
    var weekInfo = "【"+ year +"年"+ month +"月】第"+ weekday +"周 ( "+ timestampToTime(getMS(to), true) +" ) ";
    var dateItem = {"ms": getMS(to), "week": weekInfo, "crtname": weekInfo};
    return dateItem;
}

// 获取周五的时间戳
function getMS(str) {
    var newStr = str.replace(/-/g,'/');
    var date = new Date(newStr);
    return parseInt(Date.parse(date)-86400000*2);
}